<template>
  <div class="app-container">
    <br>
    <br>
    <el-button type="primary" @click="add">申请集采</el-button>
    <br>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="采购单号" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column label="采购类型" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column label="采购部门" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="品类数量" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugTypeNum }}
        </template>
      </el-table-column>
      <el-table-column label="总数量" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugNum }}
        </template>
      </el-table-column> -->
      <el-table-column label="采购时间" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.createdTime.split(' ')[0] }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusNameFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="300" >
        <template slot-scope="scope">
          <el-button type="success" :loading="toUpdateBtnLoading" @click="getInfo(scope.row)" size="small" v-if="scope.row.status === 0">修改</el-button>
          <el-button type="primary" :loading="toInfoBtnLoading"  @click="getInfo(scope.row)" size="small" v-else>详情</el-button>
          <el-button type="warning" :loading="toUpdateBtnLoading" v-if="scope.row.canAudit" @click="approve(scope.row, true)" size="small">审批</el-button>
          <el-button type="danger" :loading="toUpdateBtnLoading" v-if="scope.row.canAudit" @click="approve(scope.row, false)" size="small">拒绝</el-button>
          <!-- <el-button type="info"  @click="toCopy(scope.row)" size="small">复制</el-button> -->
          <!-- <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  </div>
</template>

<script>
import { getList, getInfo, addorupdate, del } from '@/api/purchaseOrder'
import { getListByPinyinCode, queryByCodeAnDepositoryId } from '@/api/drug'
import { getList as getSupplierList } from '@/api/supplier'
import { getChildrenDepositoryList } from '@/api/store'
import { getList as getStoreList } from '@/api/store'
import { stringToDate } from '@/utils/dateUtil'
import { audit, getList as getAuditList, getInfo as getAuditInfo } from '@/api/auditFlow'

export default {
  filters: {
    statusColorFilter(status) {
      const statusMap = ['success', 'warning', 'primary', 'danger']
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = ['草稿', '待审批', '审批完成', '已拒绝']
      return statusMap[status]
    }
  },
  data() {
    const validatePlan = (rule, value, callback) => {
      if (!value) callback(new Error('请填写计划名称')) 
      else callback()
    }
    const validateType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型'))
      else callback()
    }
    const validateDept = (rule, value, callback) => {
      if (!this.form.applyDepository) callback(new Error('请选择库'))
      else callback()
    }
    const validateSupplier = (rule, value, callback) => {
      if (!this.form.supplier) callback(new Error('请选择供货商'))
      else callback()
    }
    const validateAuditPreset = (rule, value, callback) => {
      for (let index = 0; index < this.auditPreset.length; index++) {
        if(!this.auditPreset[index].auditUser) callback(new Error('请选择审批人'))
      }
      callback()
    }
    return {
      list: null,
      listLoading: true,
      toUpdateBtnLoading: false,
      toInfoBtnLoading: false,
      commitBtnLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      dialogTitle: '',
      info: {},
      form: {},
      purchaseOrderList: [],
      typeEnum: ["集中", "临时"],
      depositoryEnum: [],
      suppliers: [],
      query: {},
      tagEnum: [{id: 1, name: '热销'},{id: 2, name: '促销'}],
      dugTypeTreeList: [],
      formRules: {
        plan: [{ required: true, trigger: 'blur', validator: validatePlan }],
        type: [{ required: true, trigger: 'blur', validator: validateType }],
        dept: [{ required: true, trigger: 'blur', validator: validateDept }],
        supplier: [{ required: true, trigger: 'blur', validator: validateSupplier }],
        auditPreset: [{ required: true, trigger: 'blur', validator: validateAuditPreset }],
      },
      searchValue: '',
      auditPreset: [],
    }
    
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var deptId = loginInfo.loginDept.deptId
      const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          deptId: deptId,
          type: '集中'
      }
      getList(reqBody).then(response => {
        console.log(response)
        this.list = response.data.records
        this.list.forEach(item=>{
          if(item.auditStatus != undefined) {
            item.status = item.auditStatus
          }
        })
        this.total = response.data.total
        this.listLoading = false
        
      })
      getSupplierList().then(supplierRes => {
        console.log(supplierRes)
        this.suppliers = supplierRes.data
      })
      getAuditInfo({businessCode: 'purchase_order'}).then(res=> {
        this.auditPreset = res.data
      })
      getChildrenDepositoryList(deptId).then(deptRes=> {
        this.depositoryEnum = deptRes.data
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    add() {
      this.$router.push({ path: '/store/purchasePage' })
    },
    getInfo(row) {
      this.$router.push({name: "PurchasePage", params: row});
    },
    deleteInfo(scope) {
      this.$confirm('确定删除该职务?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    confirm(type) {
      this.commitBtnLoading = true
      this.form.auditUserIds = this.auditPreset.map(jobDutyVo => Number(jobDutyVo.auditUser))
      console.log(this.form)
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          this.form.status = type
          addorupdate(this.form).then(res=>{
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.commitBtnLoading = false
            this.formVisible = false
            this.listLoading = false
            this.$tab.refreshPage({path: '/store/purchaseOrderAll', name: "PurchaseOrderAll"});
          }).catch(err=>{
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          this.commitBtnLoading = false
          return false
        }
      })
    },
    cancel() {
      this.infoVisible = false
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    approve(row, pass) {
      console.log(row)
      this.toUpdateBtnLoading = true
      audit({flowNo: row.code, pass: pass}).then(auditRes=> {
        console.log("auditRes", auditRes)
        this.toUpdateBtnLoading = false
        this.fetchData()
      })
    },
    toCopy(row) {
      getInfo(row.id).then(infoRes=>{
        console.log(infoRes)
        this.form = infoRes.data
        this.form.id = undefined
        this.form.status = 0
        this.form.purchaseOrderDrugList.forEach(purchase=>{
          purchase.godownDrugList = []
        })
        this.formVisible = true
      })
    },
    checkMin(drug) {
      if(drug.num < drug.minPurchaseNum) {
        this.$message.error('低于最低采购量,已自动计算');
        drug.num = drug.minPurchaseNum
      }
    },
    selectAuditUser() {

    },
  }
}

</script>

<style>
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .drug-input {
    width: 100%;
    display: inline-block;
    margin-right: 10px;
  }
  .drugs-item-title {
    line-height: 20px;
    text-align: center;
    background-color: #E4E7ED;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  .drugs-item {
    width: 140px;
    display: flex;
    flex-direction: column;
    margin-right: 10px;
  }
  .drug-name {
    width: 300px;
    word-wrap: break-word;
    margin-right: 20px;
    font-size: 15px;
    height: 58px;
    line-height: 58px;
  }
</style>